package com.lalilu.lmedia.entity

import android.net.Uri
import android.support.v4.media.MediaMetadataCompat
import com.lalilu.lmedia.extension.SourceType
import com.lalilu.lmedia.extension.albumCoverUri

data class LSong(
    override val id: String,
    override val name: String,
    val _artist: String,
    val _albumId: String,
    val _albumTitle: String,
    val _albumArtist: String?,

    val fileName: String?,
    val pathStr: String?,
    val mimeType: String,
    val durationMs: Long,
    val size: Long,
    val track: Int?,
    val disc: Int?,
    val uri: Uri,
    val dateAdded: Long?,
    val dateModified: Long?,
    val sourceType: SourceType
) : Item() {
    override fun getMatchSource(): String = "$name $_artist"

    var album: LAlbum? = null
        private set
    var dictionary: LDictionary? = null
        private set

    var artists: LinkedHashSet<LArtist> = linkedSetOf()
        private set

    var genres: LinkedHashSet<LGenre> = linkedSetOf()
        private set

    var genreId: String? = null
    var genreName: String? = null
    var artworkUri: Uri? = null
    val albumCoverUri: Uri? = runCatching { _albumId.toLong() }.getOrNull()
        ?.takeIf { it >= 0 }
        ?.albumCoverUri()

    var prefixTemp: String? = null
    var suffixTemp: String? = null

    override fun MediaMetadataCompat.Builder.initMetadata(): MediaMetadataCompat.Builder =
        this.putString(MediaMetadataCompat.METADATA_KEY_TITLE, name)
            .putString(MediaMetadataCompat.METADATA_KEY_ARTIST, _artist)
            .putString(MediaMetadataCompat.METADATA_KEY_ALBUM, _albumTitle)
            .putString(MediaMetadataCompat.METADATA_KEY_MEDIA_ID, id)
            .putString(MediaMetadataCompat.METADATA_KEY_MEDIA_URI, uri.toString())
            .putLong(MediaMetadataCompat.METADATA_KEY_DURATION, durationMs)

    fun link(album: LAlbum) {
        this.album = album
    }

    fun link(dictionary: LDictionary) {
        this.dictionary = dictionary
    }

    fun link(vararg artist: LArtist) {
        this.artists.addAll(artist)
    }

    fun link(vararg genre: LGenre) {
        this.genres.addAll(genre)
    }

    override fun requireTitle(): String = name
    override fun requireSubTitle(): String = _artist
    override fun requireItemsDuration(): Long = durationMs
    override fun requireCreateTime(): Long = dateAdded ?: 0
    override fun requireModifyTime(): Long = dateModified ?: 0
    override fun requireContentType(): String = mimeType
    override fun requireFileSize(): Long = size
    override fun requirePinyinStr(): String = pinyinMatchStr
    override fun requireDiskNumber(): Long = disc?.toLong() ?: super.requireDiskNumber()
    override fun requireTrackNumber(): Long = track?.toLong() ?: super.requireDiskNumber()
}
